package com.koron.tool;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import java.util.Map.Entry;
import java.util.List;

import javax.swing.*;
import javax.swing.filechooser.FileSystemView;
import javax.swing.plaf.metal.MetalLookAndFeel;

import com.koron.common.KVBean;
import com.koron.localdb.ConnectionBean;
import com.koron.localdb.LocalMapper;
import com.koron.mybatis.EnvSource;
import com.koron.mybatis.SessionFactory;
import com.koron.tool.frame.*;

public class MainFrame extends JFrame {
	private JDesktopPane desktop = new JDesktopPane();
	public static final Properties localDB = new Properties();
	public static HashMap<String, String> config = new HashMap<String, String>();
	public static final String RESOURCEBUDDLE = "message";

	//使用单例模式
//	private static MainFrame mainFrame = new MainFrame();
//
//	public static MainFrame getInstance(){
//		return mainFrame;
//	}

	public MainFrame() {
		super("代码生成器");
		setSize(1024, 768);
		setJMenuBar(initMenu());
		getContentPane().add(desktop);
//		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setVisible(true);
		loadConfig();
	}
	
	private JMenuBar initMenu()
	{
		JMenuBar mainMenu = new JMenuBar();
		JMenu bar = new JMenu("设置");
		//bar.add(new SelectDBAction(this));
		bar.add(new DBSettingAction(this));
		bar.add(new ProjectPropertiesAction(this));
		//bar.add(new ResourceAction(this));
		//bar.add(new SqlBeanAction(this));
		bar.add(new OneKeyTableSqlBeanAction(this));
		//bar.add(new SqlAssistantAction(this));
		//bar.add(new UserDefaineAction(this));
		//bar.add(new EnumAction(this));
		//bar.add(new EditorAction(this));
		mainMenu.add(bar);
		return mainMenu;
	}
	
	public static void loadConfig(){
		SessionFactory factory = new SessionFactory();
		List<KVBean> list =factory.getMapper(LocalMapper.class).listProperties();
		config.clear();
		config.put(Constant.ENCODE, "utf-8");
		for (KVBean kvBean : list) {
			config.put(kvBean.getKey(), kvBean.getValue());
		}
		factory.close();
	}
	
	public static void main(String[] args) {
		//设置字体
		Font font = new java.awt.Font("宋体", java.awt.Font.PLAIN, 12);
		for (Entry<?, ?> entry : UIManager.getDefaults().entrySet()) {
			if (entry.getKey().toString().toLowerCase().contains("font"))
				UIManager.put(entry.getKey(), font);
		}
		localDB.put(SessionFactory.DRIVER, "org.sqlite.JDBC");
		


        String path = getAppPath(MainFrame.class);
        path = path.substring(1);



		// String workingPath = System.getProperty("user.dir");
        String workingPath = path;
		 workingPath = workingPath.replace("\\", "/");
		 System.out.println(workingPath);

		localDB.put(SessionFactory.URL,"jdbc:sqlite:/"+workingPath+"/tool.db");
		reloadMybatis();
		try {
			UIManager.setLookAndFeel(new MetalLookAndFeel());
		} catch (UnsupportedLookAndFeelException e) {
			e.printStackTrace();
		}
		//System.setProperty("file.encoding","GBK");
		System.setProperty("file.encoding","UTF-8");
		URL u = MainFrame.class.getResource("/resource/icon.png");
		try {
			Dimension d = SystemTray.getSystemTray().getTrayIconSize();
			TrayIcon ti = new TrayIcon(Toolkit.getDefaultToolkit().createImage(u)
					.getScaledInstance(d.width, d.height, Image.SCALE_SMOOTH), "我的工具栏", new PopupMenu());
			ti.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					new MainFrame();
				}
			});
			PopupMenu popup = new PopupMenu();
			MenuItem tmp = new MenuItem("open main frame");
			tmp.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					//MainFrame.getInstance().show();
					new MainFrame();
				}
			});
			popup.add(tmp);
			tmp = new MenuItem("exit");
			tmp.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
				}
			});
			popup.add(tmp);
			ti.setPopupMenu(popup);
			SystemTray.getSystemTray().add(ti);
			//MainFrame.getInstance().show();;

		} catch (AWTException e) {
			e.printStackTrace();
		}
	}
	public static void reloadMybatis()
	{
		SessionFactory.clear();
		SessionFactory.registeDBMap(EnvSource.DEFAULT, localDB);
		SessionFactory factory = new SessionFactory();
		List<ConnectionBean> list = factory.getMapper(LocalMapper.class).list(null);
		for (ConnectionBean connectionBean : list) {
			Properties p = new Properties();
			p.put(SessionFactory.DRIVER, connectionBean.getDriver());
			p.put(SessionFactory.URL, connectionBean.getUrl());
			p.put(SessionFactory.USER, connectionBean.getUser());
			p.put(SessionFactory.PASSWORD, connectionBean.getPassword());
			SessionFactory.registeDBMap(connectionBean.getAlias(), p);
		}
		factory.close();
	}
	
	public static Connection getConnection(String alias) throws ClassNotFoundException, SQLException,NullPointerException
	{
		SessionFactory factory = new SessionFactory();
		List<ConnectionBean> list = factory.getMapper(LocalMapper.class).list(MainFrame.config.get(Constant.DATABASE_ALIAS));
		factory.close();
		if (list == null || list.isEmpty())
			throw new NullPointerException("系统未配置"+alias+"对应的数据库");
		ConnectionBean bean = list.get(0);
		Class.forName(bean.getDriver());
		Properties info = new Properties();
		info.setProperty("remarks", "true"); //设置可以获取remarks信息 
        info.setProperty("useInformationSchema", "true");
        info.setProperty("user", bean.getUser());
        info.setProperty("password", bean.getPassword());
        
		return DriverManager.getConnection(bean.getUrl(), bean.getUser(),bean.getPassword());
	}
	
	/**
	 * @return 获取#{bare_field_comment}
	 */
	public JDesktopPane getDesktop() {
		return desktop;
	}

	/**
	 * @param设置#{bare_field_comment}
	 */
	public void setDesktop(JDesktopPane desktop) {
		this.desktop = desktop;
	}



    public static String getAppPath(Class cls){
        //检查用户传入的参数是否为空
        if(cls==null)
            throw new java.lang.IllegalArgumentException("参数不能为空！");
        ClassLoader loader=cls.getClassLoader();
        //获得类的全名，包括包名
        String clsName=cls.getName()+".class";
        //获得传入参数所在的包
        Package pack=cls.getPackage();
        String path="";
        //如果不是匿名包，将包名转化为路径
        if(pack!=null){
            String packName=pack.getName();
            //此处简单判定是否是Java基础类库，防止用户传入JDK内置的类库
            if(packName.startsWith("java.")||packName.startsWith("javax."))
                throw new java.lang.IllegalArgumentException("不要传送系统类！");
            //在类的名称中，去掉包名的部分，获得类的文件名
            clsName=clsName.substring(packName.length()+1);
            //判定包名是否是简单包名，如果是，则直接将包名转换为路径，
            if(packName.indexOf(".")<0) path=packName+"/";
            else{//否则按照包名的组成部分，将包名转换为路径
                int start=0,end=0;
                end=packName.indexOf(".");
                while(end!=-1){
                    path=path+packName.substring(start,end)+"/";
                    start=end+1;
                    end=packName.indexOf(".",start);
                }
                path=path+packName.substring(start)+"/";
            }
        }
        //调用ClassLoader的getResource方法，传入包含路径信息的类文件名
        java.net.URL url =loader.getResource(path+clsName);
        //从URL对象中获取路径信息
        String realPath=url.getPath();
        //去掉路径信息中的协议名"file:"
        int pos=realPath.indexOf("file:");
        if(pos>-1) realPath=realPath.substring(pos+5);
        //去掉路径信息最后包含类文件信息的部分，得到类所在的路径
        pos=realPath.indexOf(path+clsName);
        realPath=realPath.substring(0,pos-1);
        //如果类文件被打包到JAR等文件中时，去掉对应的JAR等打包文件名
        if(realPath.endsWith("!"))
            realPath=realPath.substring(0,realPath.lastIndexOf("/"));
     /*------------------------------------------------------------
      ClassLoader的getResource方法使用了utf-8对路径信息进行了编码，当路径
       中存在中文和空格时，他会对这些字符进行转换，这样，得到的往往不是我们想要
       的真实路径，在此，调用了URLDecoder的decode方法进行解码，以便得到原始的
       中文及空格路径
     -------------------------------------------------------------*/
        try{
            realPath=java.net.URLDecoder.decode(realPath,"utf-8");
        }catch(Exception e){throw new RuntimeException(e);}
        return realPath;
    }


}
